package cn.ug.util;

import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.lang3.StringUtils;

import java.beans.PropertyDescriptor;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 公共基础方法
 * @author ywl
 * @date 2018/1/11
 */
public class Common {

    /**
     * 利用正则表达式判断字符串是否是数字
     * @param str
     * @return
     */
    public static boolean isNumeric(String str){
        if(StringUtils.isNotBlank(str)){
            Pattern pattern = Pattern.compile("[0-9]*");
            Matcher isNum = pattern.matcher(str);
            if( !isNum.matches() ){
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * 将实体转化成Map
     * @param obj
     * @return
     */
    public static Map<String, Object> beanToMap(Object obj) {
        Map<String, Object> params = new HashMap<String, Object>(0);
        try {
            PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
            PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
            for (int i = 0; i < descriptors.length; i++) {
                String name = descriptors[i].getName();
                if (!"class".equals(name)) {
                    params.put(name, propertyUtilsBean.getNestedProperty(obj, name));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return params;
    }
    /**
     * 验证手机号码是否正确
     * @param mobile
     * @return
     */
    public static boolean  validateMobile(String mobile){
        if(isEmpty(mobile)) {
            return false;
        }
        String regex = "(\\+\\d+)?1[3456789]\\d{9}$";
        return Pattern.matches(regex, mobile);
    }

    public static boolean isEmpty(String str){
        if(str == null || "".equals(str))
            return true;
        return false;
    }

    public  boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    /**
     * 验证输入的只能是中文
     * @param name
     * @return
     */
    public  boolean checkNameChinese(String name){
        boolean res=true;
        char [] cTemp = name.toCharArray();
        for(int i=0;i<name.length();i++) {
            if(!isChinese(cTemp[i])){
                res=false;
                break;
            }
        }
        return res;
    }

    /**
     * 数组转字符串
     * @param ig
     * @return
     */
    public static String converToString(String[] ig) {
        String str = "";
        if (ig != null && ig.length > 0) {
            for (int i = 0; i < ig.length; i++) {
                str += ig[i] + ",";
            }
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }
    /**
     * 数组转字符串--加引号
     * @param ig
     * @return
     */
    public static String converToSqlString(String[] ig) {
        String str = "";
        if (ig != null && ig.length > 0) {
            for (int i = 0; i < ig.length; i++) {
                str += "'"+ig[i] + "',";
            }
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }
    /**
     * 计算日期{@code startDate}与{@code endDate}的间隔天数
     *
     * @param startDate
     * @param endDate
     * @return 间隔天数
     */
    public static long until(LocalDate startDate, LocalDate endDate){
        return startDate.until(endDate, ChronoUnit.DAYS);
    }

    /**
     * 根据开始时间
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<Week> getWeekList(LocalDate startTime, LocalDate endTime) {
        List<Week> resultList = new ArrayList<Week>();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");

        //判断是否同一周
        WeekFields weekFields = WeekFields.of(DayOfWeek.MONDAY,4);
        if(startTime.get(weekFields.weekOfWeekBasedYear()) == endTime.get(weekFields.weekOfWeekBasedYear())){
            Week firstWeek = new Week();
            firstWeek.setDay(startTime + "~" + endTime);
            firstWeek.setStartTime(startTime);
            firstWeek.setEndTime(endTime);
            firstWeek.setStartTimeNumber(Integer.valueOf(df.format(startTime)));
            firstWeek.setEndTimeNumber(Integer.valueOf(df.format(endTime)));
            resultList.add(firstWeek);
            return resultList;
        }

        //开始周
        TemporalAdjuster FIRST_OF_WEEK = TemporalAdjusters.ofDateAdjuster(localDate -> localDate.minusDays(localDate.getDayOfWeek().getValue() - DayOfWeek.MONDAY.getValue()));
        LocalDate startFirstWeek = startTime.with(FIRST_OF_WEEK);  //开始周开始日期
        TemporalAdjuster LAST_OF_WEEK = TemporalAdjusters.ofDateAdjuster(localDate -> localDate.plusDays(DayOfWeek.SUNDAY.getValue() - localDate.getDayOfWeek().getValue()));
        LocalDate endFirstWeek = startTime.with(LAST_OF_WEEK);     //开始周结束日期


        //结束周
        TemporalAdjuster FIRST_OF_WEEK1 = TemporalAdjusters.ofDateAdjuster(localDate -> localDate.minusDays(localDate.getDayOfWeek().getValue() - DayOfWeek.MONDAY.getValue()));
        LocalDate startLastWeek = endTime.with(FIRST_OF_WEEK1);
        TemporalAdjuster LAST_OF_WEEK1 = TemporalAdjusters.ofDateAdjuster(localDate -> localDate.plusDays(DayOfWeek.SUNDAY.getValue() - localDate.getDayOfWeek().getValue()));
        LocalDate endLastWeek = endTime.with(LAST_OF_WEEK1);

        //将第一周添加
        Week firstWeek = new Week();
        firstWeek.setDay(startTime + "~" + endFirstWeek);
        firstWeek.setStartTime(startTime);
        firstWeek.setEndTime(endFirstWeek);
        firstWeek.setStartTimeNumber(Integer.valueOf(df.format(startTime)));
        firstWeek.setEndTimeNumber(Integer.valueOf(df.format(endFirstWeek)));
        resultList.add(firstWeek);

        while (true) {
            startFirstWeek = startFirstWeek.plusDays(7);
            if (startFirstWeek.with(LAST_OF_WEEK).equals(startLastWeek.with(LAST_OF_WEEK1))) {
                break;
            } else {
                Week week = new Week();
                week.setDay(startFirstWeek.with(FIRST_OF_WEEK) + "~" + startFirstWeek.with(LAST_OF_WEEK));
                week.setStartTime(startFirstWeek.with(FIRST_OF_WEEK));
                week.setEndTime(startFirstWeek.with(LAST_OF_WEEK));
                week.setStartTimeNumber(Integer.valueOf(df.format(startFirstWeek.with(FIRST_OF_WEEK))));
                week.setEndTimeNumber(Integer.valueOf(df.format(startFirstWeek.with(LAST_OF_WEEK))));
                resultList.add(week);
                //System.out.println("日期="+startFirstWeek+"开始周="+startFirstWeek.with(FIRST_OF_WEEK)+"结束周="+startFirstWeek.with(LAST_OF_WEEK));
            }
        }
        Week lastWeek = new Week();
        lastWeek.setDay(startLastWeek + "~" + endTime);
        lastWeek.setStartTime(startLastWeek);
        lastWeek.setEndTime(endTime);
        lastWeek.setStartTimeNumber(Integer.valueOf(df.format(startLastWeek)));
        lastWeek.setEndTimeNumber(Integer.valueOf(df.format(endTime)));
        resultList.add(lastWeek);
        return resultList;
    }

    public static void main(String[] args) {
       /*LocalDate startTime = LocalDate.parse("2018-05-02", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate endTime = LocalDate.parse("2018-06-30", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
       List<Week> list =getWeekList(startTime, endTime);//getWeekList(startTime,endTime);
       for(Week week:list){
           System.out.println("日期="+week.getDay()+"开始周="+week.getStartTime()+"结束周="+week.getEndTime()+"开始时间戳="+week.getStartTimeNumber()+"结束时间戳="+week.getEndTimeNumber());
       }*/

        LocalDate startTime = LocalDate.parse("2018-06-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate endTime = LocalDate.parse("2018-06-04", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        WeekFields weekFields = WeekFields.of(DayOfWeek.MONDAY,4);
        System.out.println(startTime.get(weekFields.weekOfWeekBasedYear()));
        System.out.println(endTime.get(weekFields.weekOfWeekBasedYear()));
    }

}
